package com.thuanpq.SQLite_Demo;

import java.io.File;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class DBAdapter {

	// The Android's default system path of your application database.
	private SQLiteDatabase myDataBase;
	private final Context myContext;
	private static final String DATABASE_CREATE = "CREATE TABLE accounts(account_name TEXT primary key,account_type TEXT not null);";
	private static final String DATABASE_NAME = Environment
			.getExternalStorageDirectory() + File.separator + "contacts.db";
	private static final String DATABASE_TABLE = "accounts";
	private static final int DATABASE_VERSION = 2;
	public static final String TAG = "DBAdapter";
	private DatabaseHelper mDbHelper;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			Log.i(TAG, "Upgrading DB");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	/**
	 * Constructor Takes and keeps a reference of the passed context in order to
	 * access to the application assets and resources.
	 * 
	 * @param context
	 */
	public DBAdapter(Context ctx) {
		this.myContext = ctx;
	}

	public DBAdapter open() {
		mDbHelper = new DatabaseHelper(myContext, DATABASE_NAME, null,
				DATABASE_VERSION);
		myDataBase = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public long createField(String name, String type) {
		// boolean flag = true;
		ContentValues inititalValues = new ContentValues();
		inititalValues.put("account_name", name);
		inititalValues.put("account_type", type);
		return myDataBase.insert("accounts", null, inititalValues);
	}

	public Cursor getAllField() {
		return myDataBase.rawQuery("SELECT * FROM accounts", null);
	}
}
